﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace Medianamik.Core.DAL.SQL
{
    public class WhereClause : ISqlQueryPart
    {
        private List<IPredicate> _predicates;
        public ReadOnlyCollection<IPredicate> Predicates
        { 
            get
            {
                return _predicates.AsReadOnly();
            }
        }

        public WhereClause(IEnumerable<IPredicate> pPredicates )
        {
            _predicates = new List<IPredicate>(pPredicates);
        }

        public WhereClause()
            :this(Enumerable.Empty<IPredicate>() )
        {

        }

        public WhereClause AddPredicate(IPredicate pPredicate)
        {
            _predicates.Add(pPredicate );
            return this;
        }

        public StringBuilder ToSQL()
        {
            if(Predicates.Count == 0)
            {
                return new StringBuilder();
            }

            var where = new StringBuilder(" WHERE ");
            where.Append(Predicates[0].ToSQL());

            foreach (var p in Enumerable.Skip(Predicates, 1))
            {
                where.AppendLine(" AND ").Append(p.ToSQL());
            }

            return where;
        }
    }
}
